<?php

namespace app\admin\controller;

use app\admin\model\AdminOperationLog;
use app\common\controller\admin\Base;
use super\Random;
use think\Cache;
use think\Controller;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

class Admin extends Controller
{


    protected $noNeedLogin = [];

    protected $model;

    private static $adminListKey = 'ADMIN_LIST_KYE:';
    private $adminLoginSalt = "#]Nti";


    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Admin;
          header('Access-Control-Allow-Origin:*');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        if ($this->request->isPost()) {
            $page = $this->request->post('page', 1);
            $size = $this->request->post('page_size', 10);
            $sort = $this->request->post('sort', 'id');
            $order = $this->request->post('order', 'desc');
            $status = $this->request->post('status', '');
            $is_bind_google = $this->request->post('is_bind_google', '');
            $username = $this->request->post('username', '');

            if ($status != '') {
                $where['status'] = $status;
            }
            if ($is_bind_google != '') {
                $where['is_bind_google'] = $is_bind_google;
            }
            if ($username != '') {
                $where['username'] = ['like', '%' . $username . '%'];
            }

            $where['is_del'] = 0;
            $list = $this->model
                ->field('id,username,avatar,logintime,loginip,create_time,status,is_bind_google')
                ->where($where)
                ->page($page, $size)
                ->order($sort, $order)
                ->select();
            foreach ($list as $k => $v) {
                $v['logintime'] = $v['logintime'] = null ? '' : $v['logintime'];
                $v['loginip'] = $v['loginip'] = null ? '' : $v['loginip'];
            }
            $total = $this->model->where($where)->count();
            $totalPage = ceil($total / $size);
            $data = [
                'total' => $total,
                'current_page' => $page,
                'total_page' => $totalPage,
                'list' => $list
            ];
            $this->success('列表', '', $data);
        }
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = $name . '.add';
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $params['salt'] = Random::alnum();
                    $params['password'] = md5(md5($params['password']) . $params['salt']);
                    $params['admin_id'] = $this->admin['id'];
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    //重置缓存
                    Cache::store('redis')->rm(self::$adminListKey);
                    $this->success('添加成功');
                } else {
                    $this->error('添加失败');
                }
            }
            $this->error('参数不能为空！');
        }
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error('不存在的数据');
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = $name . '.edit';
                        $row->validateFailException(true)->validate($validate);
                    }

                    if ($params['password'] != '') {
                        $params['password'] = md5(md5($params['password']) . $row->salt);
                    } else {
                        unset($params['password']);
                    }
                    if ($params['username'] != $row->username) {
                        $username = $this->model->where(['username' => $params['username']])->count();
                        if ($username) {
                            throw new Exception('账户名:' . $params['username'] . ' 已被使用！');
                        }
                    }
                    $params['admin_id'] = $this->admin['id'];
                    $result = $row->allowField(true)->isUpdate(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    //重置缓存
                    Cache::store('redis')->rm(self::$adminListKey);
                    $this->success('修改成功');
                } else {
                    $this->error('修改失败');
                }
            }
            $this->error('参数不能为空！');
        }
    }

    /**
     * 日志上报
     */
    public function adminOperationLog()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("");
            if ($params) {
                if (empty($params['url'])) {
                    $this->error('url参数不能为空！');
                }
                $setData = [
                    'admin_id' => $this->admin['id'],
                    'admin_username' => $this->admin['username'],
                    'url' => $params['url'],
                    'title' => empty($params['title']) ? '' : $params['title'],
                    'send_json' => empty($params['send_json']) ? '{}' : $params['send_json'],
                    'result_json' => empty($params['result_json']) ? '{}' : $params['result_json'],
                    'ip' => request()->ip()
                ];

                AdminOperationLog::create($setData);
            }
            $this->error('参数不能为空！');
        }
    }


    public function adminLogin()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if (empty($params['username'])) {
                $this->error('请输入管理员名称');
            }
            if (empty($params['password'])) {
                $this->error('请输入管理员密码');
            }
            $result = Db::table('su_admin_user')->where('password', '=', md5($this->adminLoginSalt.$params['password']))->where('username', '=', $params['username'])->find();
            if (empty($result)) {
                $this->error("账号密码错误");
            }
            $access_token = md5(uniqid() . mt_rand());
            $result['token'] = $access_token;
            $result['is_admin'] = 1;
            $result['is_kefu'] = 0;
            $result['is_leader'] = 0;
            Cache::set($access_token, $result, 86400 * 100);
            $this->success("", "", $result);
        }
    }
}
